/*********************
* Author:Dzlua
* QQ:505544956
* time:2017/07/29
*/
#include "WndCtrl.h"
#include "../edui.h"

#include <string>

EDUI_NAMESPACE_BEGIN

WndCtrl* WndCtrl::GetInterface()
{
    WndCtrl* wndCtrl = new WndCtrl;
#ifdef EDUI_TEST_NEW_DELETE
    ++m_newdeleteNum;
    Log("[WndCtrl] new wndCtrl : %d", wndCtrl);
#endif
#ifdef EDUI_USE_LUAPLUS
    LuaMgrPtr->Add("WndCtrl", wndCtrl);
#endif
    return wndCtrl;
}

void WndCtrl::Release()
{
#ifdef EDUI_TEST_NEW_DELETE
    --m_newdeleteNum;
    Log("[WndCtrl] delete wndCtrl : %s, %d", this->GetName(), this);
#endif
#ifdef EDUI_USE_LUAPLUS
    LuaMgrPtr->Remove(this);
#endif
    delete this;
}

WndCtrl::WndCtrl() : m_window(nullptr)
{}

WndCtrl::~WndCtrl()
{
    if (m_window) m_window->Close();
}

WndCtrl* WndCtrl::ToWndCtrl(Control* ctrl)
{
    return dynamic_cast<WndCtrl*>(ctrl);
}

IWindow* WndCtrl::GetInsetWindow() const {
    return m_window;
}

void WndCtrl::SetWindow(IWindow *wnd)
{
    if (m_window)
        m_window->Close();

    m_window = wnd;
    if (!m_window)
        m_window = IEnginePtr->GetWindowInterface();

    if (!m_window->IsOK()) {
        bool bOK = m_window->Create(
                std::to_string((uint64_t)this).c_str(), "WndCtrl",
                WINDOWPOS_CENTERED, WINDOWPOS_CENTERED,
                640, 480, WINDOW_BORDERLESS | WINDOW_HIDDEN);
        if (!bOK){
            m_window->Release();
            Log("[WndCtrl] : create window error.");
            m_window = nullptr;
            return;
        }
    }
    
    m_window->SetParent(this->GetWindow());

    // do not move.
    Rect rc(-1, -1, -1, -1);
    m_window->SetCaptionRect(&rc);

    // set pos and size
    rc = this->GetRect();
    auto pos = this->GetWindow()->GetPos();

    m_window->SetPos(pos.x + rc.x, pos.y + rc.y);
    m_window->SetSize(rc.w, rc.h);

    if (this->IsVisible())
        m_window->ShowWindow();
}

void WndCtrl::SetVisible(bool bVisible) {
    if (!m_window)
        return Control::SetVisible(bVisible);

    bVisible ? m_window->ShowWindow()
                : m_window->HideWindow();
    return Control::SetVisible(bVisible);
}

bool WndCtrl::SetRect(const Rect *rc) {
    if (!m_window)
        return Control::SetRect(rc);
    auto pos = this->GetWindow()->GetPos();
    m_window->SetPos(pos.x + rc->x, pos.y + rc->y);
    m_window->SetSize(rc->w, rc->h);
    return Control::SetRect(rc);
}

void WndCtrl::Render(IRender* render, const Rect* rc) {
    Control::SetRect(rc);
    if (!m_window)
        return;
    m_window->Invaldate(0);
}

EDUI_NAMESPACE_END
